package com.ymdx.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.util.CollectionUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created on 2017/9/20.
 */
public class UserFilter implements Filter {
    //    public FilterConfig config;  //获得配置的初始化话参数
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        System.out.println(servletRequest.getLocalAddr());
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String[] filterUrl = {"/user/edit", "/user/detail", "/user/product/save", "/user/product/delete" ,"/user/product/detail"};
        request.setCharacterEncoding("UTF-8");
        if (!CollectionUtils.arrayToList(filterUrl).contains(request.getRequestURI())) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            Object userId = request.getSession().getAttribute("user");
            if (userId != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {


                JSONObject responseJSONObject = new JSONObject();
                responseJSONObject.put("status", 0);
                responseJSONObject.put("code", "user_no_login");
                responseJSONObject.put("message", "用户未登陆");

                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.setContentType("application/json; charset=utf-8");
                PrintWriter out = null;
                try {
                    out = servletResponse.getWriter();
                    out.append(responseJSONObject.toJSONString());
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (out != null) {
                        out.close();
                    }
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
